// grpc服务demo
// gRPC的两个包要先intall再get
package demo

import (
	"context"
	"fmt"
	"log"
	"mediator/proto"
	"net"

	"google.golang.org/grpc"
)

func init() {
	Register("GrpcServer", func() Service {
		return new(GrpcServer)
	})

	fmt.Println("GrpcServer registered")
}

type GrpcServer struct{}

type GrpcServerServer struct {
	proto.UnimplementedAcceptorServer
}

func (s *GrpcServerServer) Election(ctx context.Context, in *proto.ElectionRequest) (*proto.ElectionResponse, error) {
	log.Printf("Received: %v", in.GetNodeId())
	return &proto.ElectionResponse{ElectionStatus: 1}, nil
}

func (gs *GrpcServer) Exec() {
	// grpc demo
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		fmt.Printf("failed to grpc_server listen: %v\n", err)
	}

	s := grpc.NewServer()
	proto.RegisterAcceptorServer(s, &GrpcServerServer{})
	fmt.Printf("server listening at %v\n", lis.Addr())
	if err := s.Serve(lis); err != nil {
		fmt.Printf("failed to grpc_server serve: %v\n", err)
	}
}
